package de.pharmacontrol.psa.controller;

import java.sql.Timestamp;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.Date;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;

import org.primefaces.model.DefaultScheduleEvent;
import org.primefaces.model.LazyScheduleModel;
import org.primefaces.model.ScheduleModel;

import de.pharmacontrol.pilot.entities.Order;
import de.pharmacontrol.psa.beans.interfaces.OrderService;

@ManagedBean
public class ScheduleController {

	@EJB
	OrderService orderBean;

	private ScheduleModel lazyEventModel;

	public ScheduleController() {

		lazyEventModel = new LazyScheduleModel() {

			private static final long serialVersionUID = 1L;

			public void loadEvents(Date start, Date end) {
				clear();
				Timestamp startTs = new Timestamp(start.getTime());
				Timestamp endTs = new Timestamp(end.getTime());
				Collection<Order> oderList = orderBean.findOrderByCreateTime(startTs, endTs);
				for (Order od : oderList) {
					DefaultScheduleEvent event = new DefaultScheduleEvent(getEventMessage(od), od.getCreated(), od.getCreated(), od);
					event.setAllDay(false);
					addEvent(event);
				}

			};

		};
	}

	public String getEventMessage(Order order) {
		String line = null;
		if (order.getLineFormat() != null && order.getLineFormat().getLine() != null) {
			line = order.getLineFormat().getLine().getName();
		}
		String msg = null;
		if (order.isAutoImported()) {
			msg = MessageFormat.format("Order: {0} imported {1}", order.getName(), (line != null ? "on line: " + line : ""));
		} else {
			msg = MessageFormat.format("Order: {0} created {1}", order.getName(), (line != null ? "on line: " + line : ""));
		}
		return msg;
	}

	public ScheduleModel getLazyEventModel() {
		return lazyEventModel;
	}
}
